#include "server.h"

Server::Server(sockaddr *addr)
{
    base_ = event_base_new();
    listener_ = evconnlistener_new_bind(
        base_,
        AcceptCallback,
        NULL,
        LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_FREE,
        -1,
        (struct sockaddr *)&addr,
        sizeof(*addr));
}

void Server::Start()
{
    event_base_dispatch(base_);
}

void Server::AcceptCallback(struct evconnlistener *listener, evutil_socket_t fd, struct sockaddr *addr, int socklen, void *arg)
{
    // 创建bufferevent
    struct event_base *base = evconnlistener_get_base(listener);
    struct bufferevent *bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);

    // 设置读取回调函数
    bufferevent_setcb(bev, ReadCallback, NULL, ErrorCallback, NULL);

    // 开始监听读取事件
    bufferevent_enable(bev, EV_READ | EV_WRITE);
}

void Server::ReadCallback(struct bufferevent *bev, void *arg)
{
    // 读取数据并处理
    char buf[1024];
    size_t len = bufferevent_read(bev, buf, sizeof(buf) - 1);
    buf[len] = '\0';
    printf("Received data: %s\n", buf);

    // 发送响应数据
    const char *response = "Hello, client!";
    bufferevent_write(bev, response, strlen(response));
}

void Server::ErrorCallback(struct bufferevent *bev, short error, void *arg)
{
    if (error & BEV_EVENT_EOF)
    {
        // 连接已关闭
    }
    else if (error & BEV_EVENT_ERROR)
    {
        // 发生错误
    }
    else if (error & BEV_EVENT_TIMEOUT)
    {
        // 发生超时
    }

    bufferevent_free(bev);
}
